import Request from "@/api/request";
import store from "@/store";
import { Project } from "@/interface/entity";
import {
  processProjectBeforeToDb,
  generateProjectLists
} from "@/functions/project";
// add project to db
export async function addProjectToDb(project: Project) {
  // before to db
  const projectToDb = processProjectBeforeToDb(project, "add");

  // console.log("project", projectToDb);

  await Request({
    method: "post",
    url: "Project/AddProject",
    data: JSON.stringify(projectToDb)
  });
}
// add many projects when uploading
export async function addUploadedProjectToDb(projects: Project[]) {
  // console.log("projecttodb", projects);
  await Request({
    method: "post",
    url: "Project/AddPrjectList",
    data: JSON.stringify(projects)
  });
}
// delete project
export async function deleteProjectFromDb(project: Project) {
  await Request({
    method: "delete",
    url: "Project/DeleteProject",
    params: {
      projectGuid: project.projectGuid
    }
  });
}

// get project list of a user. Will called when first see the "myproject" page
// will be shown in the table
export async function queryProjectListByUserName(username: string) {
  // error will be catched in the response inspector
  // return [];
  Request({
    method: "get",
    url: "Project/QueryProjectsByUserName",
    params: {
      username: username
    }
  })
    .then(response => {
      store.state.projectList = generateProjectLists(
        response.data as Project[]
      );
    })
    .catch(() => {
      return [];
    });
}

// get all project
export async function queryAllProject() {
  await Request({
    method: "get",
    url: "Project/QueryAllProject"
  }).then(response => {
    store.state.tableData = generateProjectLists(response.data as Project[]);
    store.state.projectList = generateProjectLists(response.data as Project[]);
  });

  // error will be catched in the response inspector
  return [];
}

// query a project(when project is updated in db) and process so that it can be shown in the project table

// save change of the selected project in db
export async function updateProjectToDb(project: Project) {
  // bufore to db
  const projectToDb = processProjectBeforeToDb(project);
  // ....
  await Request({
    method: "put",
    url: "Project/UpdateProject",
    data: JSON.stringify(projectToDb)
  });
}
